let models = require('node-require-directory')(__dirname);
let mongoose = require('mongoose');
let config = require('config');
let Promise = require('bluebird');
let findOrCreate = require('mongoose-findorcreate');

mongoose.Promise = Promise;

mongoose.connect('mongodb://' + config.mongodb.host + '/' + config.mongodb.database);
// global.mongooseConnection = mongoose.createConnection('mongodb://' + config.mongodb.host + '/' + config.mongodb.database);
// global.mongooseConnection.open('mongodb://' + config.mongodb.host + '/' + config.mongodb.database);
global.mongooseConnection = mongoose.connection;

function recurseModels(models, parentFolder) {
    let folders = [];
    Object.keys(models).forEach(function (key) {
        if (key === 'index') return;
        // if (typeof(models[key]) === 'object') {
        if (models[key] instanceof mongoose.Schema) {
            // file
            // add find or create static method
            models[key].plugin(findOrCreate);
            let modelName = capitaliseFirstLetter(key);
            // length must > 1
            if (parentFolder && parentFolder.length > 1) {
                // discriminator
                // last chat is &, ignore it
                let parentModelName = capitaliseFirstLetter(parentFolder.substr(0, parentFolder.length - 1));

                if (global[parentModelName]) {
                    global[modelName] = global[parentModelName].discriminator(modelName, models[key]);
                }
            } else {
                global[modelName] = mongoose.model(modelName, models[key]);
            }
            // promise
            Promise.promisifyAll(global[modelName]);
            Promise.promisifyAll(global[modelName]);
        } else {
            // folder
            folders.push(key);
        }

    });
    // recurse folder
    for (let i = 0; i < folders.length; i++) {
        let folder = folders[i];
        recurseModels(models[folder], folder);
    }
}


recurseModels(models);

global.mongoose = mongoose;

function capitaliseFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}
